<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 每日菜单
 * @author heyu
 */
class DailyMenus extends MY_Controller {
    /**
     * @var AdmDailyMenusModel
     */
    public $mDailyMenus;

	public function __construct(){
		parent::__construct();
        $this->loadModel('AdmDailyMenusModel', 'mDailyMenus', 'admin');
	}
	
	/**
	 * 首页
	 */
	public function index(){
        $data = array(
            'recommend' => $this->getStatus(),
            'title' => '每日菜单'
        );
		$this->view('dailyMenus/home', $data, 'datepicker,select2,datatable,validation,datepicker');
	}
	
	/**
	 * 获取列表
	 */
	public function getList(){
		$data = $this->mDailyMenus->adminPcGetList();
        foreach ($data['data'] as $k => $v){
            $img = isset($v['pic']) ? getImage($v['pic'], 'xs') : getDefaultPortrait();
            $data['aaData'][$k][] = '<img src="'.$img.'" class="portrait img-wh"/>';
            $data['aaData'][$k][] = $v['title'];
            $recommend = $v['is_recommend'] == 1 ? 2 : 1;
            $data['aaData'][$k][] = adminCreateBtn(array(
                'label' => $this->getStatus($v['is_recommend'], true),
                'icon' => '',
                'attr' => array(
                    'href' => getUrl('dailyMenus/changeStatus?id='.$v['id']),
                    'class' => 'ajax-request-btn deco',
                    'alert-message' => '是否设置为'.$this->getStatus($recommend)
                ),
                'tag' => 'a',
                'permissions' => array(
                    'module' => 'dailyMenus',
                    'key' => 'dailyMenus-edit'
                )
            ));
            $data['aaData'][$k][] = dateFormat($v['addtime']);
            $btnConfig = adminCreateBtn(array(
                'label' => ' 编辑',
                'icon' => '',
                'attr' => array(
                    'href' => getUrl('dailyMenus/edit?id='.$v['id']),
                    'class' => 'btn default btn-xs blue-stripe',
                ),
                'tag' => 'a',
                'permissions' => array(
                    'module' => 'dailyMenus',
                    'key' => 'dailyMenus-edit'
                )
            ));
            $btnConfig .= ' '.adminCreateBtn(array(
                'label' => ' 删除',
                'icon' => '',
                'attr' => array(
                    'href' => getUrl('dailyMenus/delete?id='.$v['id']),
                    'class' => 'ajax-request-btn btn default btn-xs red-stripe',
                    'alert-message' => "确认要删除吗？"
                ),
                'tag' => 'a',
                'permissions' => array(
                    'module' => 'dailyMenus',
                    'key' => 'dailyMenus-delete'
                )
            ));
            $data['aaData'][$k][] = $btnConfig;
        }
        unset($data['data']);
        echo json_encode($data);
	}

    /**
     * 添加
     */
    public function add(){
        $data = array(
            'add' => true,
            'title' => '添加'
        );
        $this->view('dailyMenus/from', $data, 'validation,datepicker,select2,cropit_master,ueditor');
    }

    /**
     * 编辑
     */
    public function edit(){
        $id = (int)get('id');
        if (!$id){
            show_404();
        }
        $info = $this->mDailyMenus->getInfo($id);

        $data = array(
            'info' => $info,
            'add' => false,
            'title' => '编辑'
        );
        $this->view('dailyMenus/from', $data, 'validation,datepicker,select2,cropit_master,ueditor');
    }

    /**
     * 保存
     */
    public function save(){
        //表单验证
        $vConf = array(
            array('title', '菜谱名称', 'required'),
            array('production_time', '制作时间', 'required'),
            array('desc', '简介', 'required'),
            array('is_recommend', '是否推荐', 'required|in_list[1,2]'),
            array('content', '内容', 'required'),
        );
        $this->formDataValidation($vConf);
        $id = (int)post('id');
        $images = post('icon');
        if (!$id && empty($images)){
            $this->ajaxReturn(0, '请上传图片');
        }

        $data = array(
            'title' => trim(post('title')),
            'desc' => trim(post('desc')),
            'production_time' => trim(post('production_time')),
            'is_recommend' => post('is_recommend'),
        );
        $this->db->trans_begin();
        if( ! $id){
            $data['addtime'] = time();
            if( ! ($id = $this->mDailyMenus->save($data))){
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '保存失败');
            }
        }else{
            $info = $this->mDailyMenus->getInfo($id);
            if (!$info){
                $this->ajaxReturn(0, '数据不存在');
            }
        }

        if ( $images){
            //上传封面图
            $path = 'uploads/dailyMenus/'.$id;
            $tA = saveCSVimg(array($images), $path, 'pic');
            if( ! $tA){
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '封面图上传失败');
            }
            $data['pic'] = $tA[0];
        }
        $path = 'uploads/dailyMenus/content/'.$id;
        $data['content'] = saveEditerTempImg(trim(post('content')), $path);
        if($data['content'] === false){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '保存失败');
        }

        $query = $this->mDailyMenus->save($data, $id);
        if( ! $query){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '保存失败');
        }

        $this->db->trans_commit();
        $this->ajaxReturn(1, '保存成功', null, getUrl('dailyMenus'));
    }

    /**
     * 删除
     */
    public function delete()
    {
        //表单验证
        $vConf = array(
            array('id', '反馈id', 'required|is_natural'),
        );
        $this->formDataValidation($vConf, array('id' => get('id')));
        $id = (int)get('id');
        $info = $this->mDailyMenus->getInfo($id);
        if (!$info){
            $this->ajaxReturn(0, '数据不存在或已删除');
        }
        $tId=$this->mDailyMenus->deleteDailyMenus($id);
        if(! $tId){
            $this->ajaxReturn(0,'删除失败');
        }
        // 删除图片
        $v = strstr($info['pic_og'], '?',true);
        $file = substr($v, 0, strripos($v, '/'));
        if (file_exists($v)){
            @unlink($v);
        }
        if (file_exists($file)){
            @rmdir($file);
        }
        $this->ajaxReturn(1,'删除成功');
    }

    /**
     * 修改状态
     */
    public function changeStatus(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf, array('id' => get('id')));
        $id = (int)get('id');
        $info = $this->mDailyMenus->getInfo($id);
        if (!$info){
            $this->ajaxReturn(0, '数据不存在');
        }
        $status = $info['is_recommend'] == 1 ? 2 : 1;
        $tA = $this->mDailyMenus->save(array('is_recommend' => $status), $id);
        if (!$tA){
            $this->ajaxReturn(0, '保存失败');
        }
        $this->ajaxReturn(1, '保存成功');
    }

    /**
     * 获取状态
     *
     * @param	integer	$key
     * @param	boolean	$show	是否显示
     * @return	mixed
     */
    public function getStatus($key = null, $show = false){

        $config = array(
            1 => '普通',
            2 => '推荐',
        );

        if($key !== null){

            if(isset($config[$key]) && ! $show){
                return $config[$key];
            }

            if(isset($config[$key]) && $show){

                if($key == 1){
                    return '<span class="label label-danger">'.$config[$key].'</span>';
                }else if($key == 2){
                    return '<span class="label label-success">'.$config[$key].'</span>';
                }
            }
            return '';
        }

        return $config;
    }
}
